
// @koala-prepend "../../../libs/config.js"

$(function(){
    var isLogin = urls.checklogin();
    if(!isLogin) {
        $('.alert-title').html('未登录，请先登录');
        var $dialog = $('.modal-alert');
        $dialog.show();
        $dialog.find('.weui_btn_dialog').unbind('click').bind('click', function () {
            location.href = '../../login';          
        });
        setTimeout(function(){
            location.href = '../../login';
        }, 3000);
        return;
    }
    Page.token = urls.GetQueryString('t');
    $('a.to-merchants').attr('href', '../merchants?t=' + Page.token);



    Page.id = urls.GetQueryString('key');
	$('.btn-sure').click(Page.Sure);
    if(Page.id != '') {
        Page.loadData();        
    }
    else {
        $('.logo .title').html('新增商家');
        $('.merchants-number').hide();
        $('.box').css('height', '190px');
    }
});

var Page = {};
Page.loadData = function() {
    var url = urls.server + '/merchants/' + Page.id;
    $.ajax({
        type: 'GET',
        async: true,
        url: url,
        dataType: 'json',
        data: {
            id: Page.id
        },
        success: function(e){
            if(e && e.id) {
                $('.txt-name').val(e.name);
                $('.txt-number').html(e.number);
                $('.txt-phone').val(e.phone);
            }
        }
    });
}
Page.Sure = function() {
	var name = $.trim($('.txt-name').val());
	if(name == '') {
		$('.pophint').html('请输入商家名称');
		$('.modal-hint').modal('show');
		return;
	}

	var phone = $.trim($('.txt-phone').val());
	if(phone == '') {
		$('.pophint').html('请输入商家编号');
		$('.modal-hint').modal('show');
		return;
	}
    var url = urls.server + '/merchants';
    var param = {
        name: name,
        phone: phone,
        access_token: 'AABBCCDD'
    };
    if( Page.id != '' ) {
        url += '/' + Page.id;
        param.id = Page.id;
    }

    $('.btn-sure').unbind('click').html('正在处理...');
	$.ajax({
        type: (Page.id == '' ? 'POST' : 'PUT'),
        async: true,
        url: url,
        dataType: 'json',
        data: param,
        success: function(e){
            $('.btn-sure').click(Page.Sure).html('提交');
        	if(e && e.id) {                
                $('.pophint').html(Page.id == '' ? '新增商家成功' : '编辑商家成功');
                $('.modal-hint').on('hidden.bs.modal', function (e) {
                    location.href = '../?t=' + Page.token;
                });
                $('.modal-hint').modal('show');
                return;
            }
        }
    });
	
}